package com.example.projectmanagement.controller.study;

import com.example.projectmanagement.dto.study.QuestionDto;
import com.example.projectmanagement.dto.study.AnswerDto;
import com.example.projectmanagement.dto.study.DashboardDataDto;
import com.example.projectmanagement.model.study.Question;
import com.example.projectmanagement.model.study.Answer;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.repository.study.AnswerRepository;
import com.example.projectmanagement.service.study.QuestionService;
import com.example.projectmanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/study/questions")
@CrossOrigin
public class QuestionController {

    @Autowired
    private QuestionService questionService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private AnswerRepository answerRepository;

    /**
     * 创建问题
     */
    @PostMapping
    public ResponseEntity<Question> createQuestion(@RequestBody Question question) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            // 安全地获取courseId
            Long courseId = null;
            // 检查是否直接传递了courseId
            if (question.getCourse() != null && question.getCourse().getId() != null) {
                courseId = question.getCourse().getId();
            } else if (question.getCourseId() != null) {
                // 如果前端直接传递了courseId字段
                courseId = question.getCourseId();
            }
            
            Question createdQuestion = questionService.createQuestion(question, userOpt.get(), courseId);
            return ResponseEntity.ok(createdQuestion);
        } catch (Exception e) {
            e.printStackTrace(); // 打印错误信息以便调试
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 更新问题
     */
    @PutMapping("/{id}")
    public ResponseEntity<Question> updateQuestion(@PathVariable Long id, @RequestBody Question questionDetails) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Question updatedQuestion = questionService.updateQuestion(id, questionDetails, userOpt.get());
            return ResponseEntity.ok(updatedQuestion);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取问题分页列表
     */
    @GetMapping
    public ResponseEntity<Page<QuestionDto>> getQuestions(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long courseId,
            @RequestParam(required = false) Long lessonId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String sort) {
        
        // 处理空字符串参数
        if (courseId != null && courseId <= 0) {
            courseId = null;
        }
        
        if (status != null && status.isEmpty()) {
            status = null;
        }
        
        if (keyword != null && keyword.isEmpty()) {
            keyword = null;
        }
        
        // 构建Pageable对象
        Pageable pageable;
        if (sort != null && !sort.isEmpty()) {
            try {
                // 解析sort参数，格式为"field,direction"
                String[] sortParts = sort.split(",");
                if (sortParts.length == 2) {
                    org.springframework.data.domain.Sort.Direction direction = 
                        org.springframework.data.domain.Sort.Direction.fromString(sortParts[1]);
                    pageable = PageRequest.of(page, size, org.springframework.data.domain.Sort.by(direction, sortParts[0]));
                } else {
                    pageable = PageRequest.of(page, size);
                }
            } catch (Exception e) {
                // 如果解析失败，使用默认排序
                pageable = PageRequest.of(page, size);
            }
        } else {
            pageable = PageRequest.of(page, size);
        }
        
        Page<Question> questions;
        if (courseId != null && lessonId != null && lessonId > 0) {
            questions = questionService.getQuestionsByCourseAndLesson(courseId, lessonId, pageable);
        } else if (courseId != null) {
            questions = questionService.getQuestionsByCourse(courseId, pageable);
        } else if (status != null && !status.isEmpty()) {
            questions = questionService.getQuestionsByStatus(status, pageable);
        } else if (keyword != null && !keyword.isEmpty()) {
            questions = questionService.searchQuestions(keyword, pageable);
        } else {
            questions = questionService.getQuestions(pageable);
        }
        
        Page<QuestionDto> questionDtos = questions.map(this::convertToQuestionDto);
        return ResponseEntity.ok(questionDtos);
    }

    /**
     * 根据ID获取问题
     */
    @GetMapping("/{id}")
    public ResponseEntity<QuestionDto> getQuestionById(@PathVariable Long id) {
        Optional<Question> question = questionService.getQuestionById(id);
        return question.map(q -> ResponseEntity.ok(convertToQuestionDto(q)))
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 增加问题浏览次数
     */
    @PutMapping("/{id}/view")
    public ResponseEntity<Void> incrementViewCount(@PathVariable Long id) {
        questionService.incrementViewCount(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除问题
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteQuestion(@PathVariable Long id) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            questionService.deleteQuestion(id, userOpt.get(), userService);
            return ResponseEntity.ok("问题删除成功");
        } catch (RuntimeException e) {
            // 返回具体的错误信息
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除问题失败: " + e.getMessage());
        }
    }

    /**
     * 更新问题状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<Question> updateQuestionStatus(@PathVariable Long id, @RequestParam String status) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Question updatedQuestion = questionService.updateQuestionStatus(id, status, userOpt.get());
            return ResponseEntity.ok(updatedQuestion);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 问题点赞
     */
    @PostMapping("/{id}/like")
    public ResponseEntity<QuestionDto> likeQuestion(@PathVariable Long id) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Question updatedQuestion = questionService.likeQuestion(id, userOpt.get());
            QuestionDto questionDto = convertToQuestionDto(updatedQuestion);
            return ResponseEntity.ok(questionDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 检查用户是否已点赞问题
     */
    @GetMapping("/{id}/liked")
    public ResponseEntity<Boolean> isQuestionLikedByUser(@PathVariable Long id) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            boolean isLiked = questionService.isQuestionLikedByUser(id, userOpt.get());
            return ResponseEntity.ok(isLiked);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 问题取消点赞
     */
    @PostMapping("/{id}/unlike")
    public ResponseEntity<QuestionDto> unlikeQuestion(@PathVariable Long id) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Question updatedQuestion = questionService.unlikeQuestion(id, userOpt.get());
            QuestionDto questionDto = convertToQuestionDto(updatedQuestion);
            return ResponseEntity.ok(questionDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 创建回答
     */
    @PostMapping("/{questionId}/answers")
    public ResponseEntity<AnswerDto> createAnswer(@PathVariable Long questionId, @RequestBody Answer answer) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Answer createdAnswer = questionService.createAnswer(answer, userOpt.get(), questionId);
            AnswerDto answerDto = convertToAnswerDto(createdAnswer);
            return ResponseEntity.ok(answerDto);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 更新回答
     */
    @PutMapping("/answers/{id}")
    public ResponseEntity<AnswerDto> updateAnswer(@PathVariable Long id, @RequestBody Answer answerDetails) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Answer updatedAnswer = questionService.updateAnswer(id, answerDetails, userOpt.get());
            AnswerDto answerDto = convertToAnswerDto(updatedAnswer);
            return ResponseEntity.ok(answerDto);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取问题的所有回答
     */
    @GetMapping("/{questionId}/answers")
    public ResponseEntity<Page<AnswerDto>> getAnswersByQuestion(
            @PathVariable Long questionId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Answer> answers = questionService.getAnswersByQuestion(questionId, pageable);
        Page<AnswerDto> answerDtos = answers.map(this::convertToAnswerDto);
        return ResponseEntity.ok(answerDtos);
    }

    /**
     * 删除回答
     */
    @DeleteMapping("/answers/{id}")
    public ResponseEntity<String> deleteAnswer(@PathVariable Long id) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            questionService.deleteAnswer(id, userOpt.get(), userService);
            return ResponseEntity.ok("回答删除成功");
        } catch (RuntimeException e) {
            // 返回具体的错误信息
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除回答失败: " + e.getMessage());
        }
    }
    
    /**
     * 回答点赞
     */
    @PostMapping("/answers/{id}/like")
    public ResponseEntity<AnswerDto> likeAnswer(@PathVariable Long id) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Answer updatedAnswer = questionService.likeAnswer(id, userOpt.get());
            AnswerDto answerDto = convertToAnswerDto(updatedAnswer);
            return ResponseEntity.ok(answerDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 回答取消点赞
     */
    @PostMapping("/answers/{id}/unlike")
    public ResponseEntity<AnswerDto> unlikeAnswer(@PathVariable Long id) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Answer updatedAnswer = questionService.unlikeAnswer(id, userOpt.get());
            AnswerDto answerDto = convertToAnswerDto(updatedAnswer);
            return ResponseEntity.ok(answerDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 检查用户是否已点赞回答
     */
    @GetMapping("/answers/{id}/liked")
    public ResponseEntity<Boolean> isAnswerLikedByUser(@PathVariable Long id) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            boolean isLiked = questionService.isAnswerLikedByUser(id, userOpt.get());
            return ResponseEntity.ok(isLiked);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 采纳回答为最佳答案
     */
    @PostMapping("/answers/{id}/accept")
    public ResponseEntity<Object> acceptAnswer(@PathVariable Long id) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).body("用户未认证");
        }
        
        try {
            // 先获取完整的用户信息，避免懒加载问题
            Optional<User> userOpt = userService.getUserById(currentUserId);
            if (!userOpt.isPresent()) {
                return ResponseEntity.status(401).body("用户认证信息无效");
            }
            
            User currentUser = userOpt.get();
            
            try {
                Answer acceptedAnswer = questionService.acceptAnswer(id, currentUser);
                // 为了避免任何懒加载问题，在这里重新获取answer以确保对象完整
                if (acceptedAnswer != null) {
                    // 重新获取完整对象，避免任何懒加载问题
                    Answer freshAnswer = answerRepository.findById(acceptedAnswer.getId())
                            .orElseThrow(() -> new RuntimeException("回答不存在"));
                    AnswerDto answerDto = convertToAnswerDto(freshAnswer);
                    return ResponseEntity.ok(answerDto);
                }
                return ResponseEntity.badRequest().body("采纳回答失败");
            } catch (RuntimeException e) {
                // 处理权限相关的运行时异常
                if (e.getMessage().contains("permission")) {
                    return ResponseEntity.status(403).body(e.getMessage());
                }
                return ResponseEntity.badRequest().body(e.getMessage());
            } catch (Exception e) {
                // 处理其他异常
                return ResponseEntity.badRequest().body("采纳回答失败: " + e.getMessage());
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body("服务器内部错误: " + e.getMessage());
        }
    }

    /**
     * 获取仪表板数据
     */
    @GetMapping("/dashboard")
    public ResponseEntity<DashboardDataDto> getDashboardData(@RequestParam(defaultValue = "7d") String timeRange) {
        DashboardDataDto dashboardData = questionService.getDashboardData(timeRange);
        return ResponseEntity.ok(dashboardData);
    }


    /**
     * 根据用户ID获取回答分页列表
     */
    @GetMapping("/answers")
    public ResponseEntity<Page<AnswerDto>> getAnswersByUser(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Optional<User> userOpt = userService.getUserById(userId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.badRequest().build();
        }
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Answer> answers = questionService.getAnswersByUser(userOpt.get(), pageable);
        Page<AnswerDto> answerDtos = answers.map(this::convertToAnswerDto);
        return ResponseEntity.ok(answerDtos);
    }

    /**
     * 获取当前认证用户的ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            return userService.getUserByUsername(username).map(User::getId).orElse(null);
        }
        return null;
    }

    /**
     * 转换Question到QuestionDto
     */
    private QuestionDto convertToQuestionDto(Question question) {
        QuestionDto dto = new QuestionDto();
        dto.setId(question.getId());
        dto.setTitle(question.getTitle());
        dto.setContent(question.getContent());
        if (question.getUser() != null) {
            dto.setUserId(question.getUser().getId());
            dto.setUserName(question.getUser().getName());
        }
        if (question.getCourse() != null) {
            dto.setCourseId(question.getCourse().getId());
            dto.setCourseTitle(question.getCourse().getTitle());
        }
        dto.setLessonId(question.getLessonId());
        // 设置内容类型（目前默认为LESSON，实际应用中可能需要根据业务逻辑判断）
        dto.setContentType("LESSON");
        dto.setViewCount(question.getViewCount());
        dto.setAnswerCount(question.getAnswerCount());
        dto.setLikeCount(question.getLikeCount());
        dto.setStatus(question.getStatus());
        dto.setCreateTime(question.getCreateTime());
        dto.setUpdateTime(question.getUpdateTime());
        return dto;
    }

    /**
     * 安全转换Answer到AnswerDto - 避免懒加载问题
     */
    private AnswerDto convertToAnswerDto(Answer answer) {
        AnswerDto dto = new AnswerDto();
        dto.setId(answer.getId());
        dto.setContent(answer.getContent());
        
        // 避免访问懒加载的user对象，改用直接设置ID和名称
        // 这样可以避免Hibernate懒加载异常
        if (answer.getUser() != null) {
            // 强制加载用户信息
            try {
                Long userId = answer.getUser().getId();
                String userName = answer.getUser().getName();
                dto.setUserId(userId);
                dto.setUserName(userName);
            } catch (Exception e) {
                // 如果懒加载失败，使用默认值
                dto.setUserId(null);
                dto.setUserName("未知用户");
            }
        }
        
        if (answer.getQuestion() != null) {
            dto.setQuestionId(answer.getQuestion().getId());
        }
        
        // 设置parentAnswerId
        if (answer.getParentAnswer() != null) {
            dto.setParentAnswerId(answer.getParentAnswer().getId());
        } else if (answer.getParentAnswerId() != null) {
            dto.setParentAnswerId(answer.getParentAnswerId());
        }
        
        // 设置其他字段
        dto.setLikeCount(answer.getLikeCount());
        dto.setDislikeCount(answer.getDislikeCount());
        dto.setIsAccepted(answer.getIsAccepted());
        dto.setCreateTime(answer.getCreateTime());
        dto.setUpdateTime(answer.getUpdateTime());
        return dto;
    }
}